package com.yuan.aop;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
public class MyLogging {

//    @Before("execution(* com.yuan.aop.CalcImpl2.add(..))")
//    @Before("com.yuan.mypointcut.MyPointCut.myPointCut()")
    public void methodBefore(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("前置通知：==>"+methodName+"()正在执行,参数:"+ Arrays.toString(args));
    }

//    @After("com.yuan.mypointcut.MyPointCut.myPointCut()")
    public void methodAfter(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("后置通知：==>"+methodName+"()正在执行,参数:"+ Arrays.toString(args));
    }

//    @AfterReturning(value = "com.yuan.mypointcut.MyPointCut.myPointCut()",returning = "rs")
    public void methodAfterReturning(JoinPoint joinPoint,Object rs){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("返回通知：==>"+methodName+"()返回的结果："+ rs);
    }

//    @AfterThrowing(value = "com.yuan.mypointcut.MyPointCut.myPointCut()",throwing = "ex")
    public void methodAfterThrowing(JoinPoint joinPoint,Exception ex){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("异常通知：==>"+methodName+"(),异常的ex:"+ ex);
    }

    @Around("com.yuan.mypointcut.MyPointCut.myPointCut()")
    public Object methodAround(ProceedingJoinPoint pjp) {
        String methodName = pjp.getSignature().getName();
        Object[] args = pjp.getArgs();
        Object rs = null;
        try {
            //前置通知
            System.out.println("前置通知==>"+methodName+"()正在执行,参数:"+ Arrays.toString(args));
            // 执行目标方法,如:add() sub() mul() div()
            rs = pjp.proceed();
            //返回通知
            System.out.println("返回通知==>"+methodName+"()方法返回结果rs:"+rs);
        } catch (Throwable e) {
            //异常通知
            System.out.println("异常通知==>"+methodName+"()方法的异常ex:"+e);
            throw new RuntimeException(e);
        } finally {
            //后置通知
            System.out.println("后置通知==>"+methodName+"()执行完毕!");
        }
        return rs;
    }
}
